/*
 * @author : TF-BJ-C064
 * @creation : 2014-8-6 下午8:50:49
 * @description : 
 *
 */

package com.umeng;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class UMLoginAction {

	public Logger log = Logger.getLogger(UMLoginAction.class);

	public static String LOGIN_URL = "https://www.umeng.com/sso/login";

	private UMUser user;
	String html;
	
	HttpClient httpclient = new DefaultHttpClient();
	Header[] cookieHeaders;
	HttpGet get = null;
	HttpPost post = null;
	HttpResponse httpResponse;

	public UMLoginAction(){
	}

	public void index() throws ClientProtocolException, IOException{
		//让服务器知道访问源为浏览器 
		httpclient.getParams().setParameter(HttpMethodParams.USER_AGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36");
		get = new HttpGet(LOGIN_URL);
		httpResponse = httpclient.execute(get);
		html = EntityUtils.toString(httpResponse.getEntity());
		cookieHeaders = httpResponse.getHeaders("Set-Cookie");
		user.setCookie(cookieHeaders);
		get.releaseConnection();

		Document htmljsoup = Jsoup.parse(html);

		Element form  =htmljsoup.getElementById("login-form");
		if(form==null)
			log.info(html);
		else
			log.info(form.html());
		
		Element ltE = form.getElementById("lt");
		user.setLt(ltE.attr("value"));
		Element serviceE = form.getElementById("service");
		user.setService(serviceE.attr("value"));

	}

	public boolean login() throws ClientProtocolException, IOException, KeyManagementException, NoSuchAlgorithmException{
		
	    //Secure Protocol implementation.  
//        SSLContext ctx = SSLContext.getInstance("TLS");  
//                    //Implementation of a trust manager for X509 certificates  
//        X509TrustManager tm = new X509TrustManager() {  
//            public void checkClientTrusted(X509Certificate[] xcs,  
//                    String string) throws CertificateException {  
//            }  
//            public void checkServerTrusted(X509Certificate[] xcs,  
//                    String string) throws CertificateException {  
//            }  
//            public X509Certificate[] getAcceptedIssuers() {  
//                return null;  
//            }  
//        };  
//        ctx.init(null, new TrustManager[] { tm }, null);  
//        SSLSocketFactory ssf = new SSLSocketFactory(ctx);  
//
//        ClientConnectionManager ccm = httpclient.getConnectionManager();  
//        //register https protocol in httpclient's scheme registry  
//        SchemeRegistry sr = ccm.getSchemeRegistry();  
//        sr.register(new Scheme("https", 443, ssf));  

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("username", user.getUsername()) );
		params.add(new BasicNameValuePair("password", user.getPassword()) );
		params.add(new BasicNameValuePair("lt", user.getLt()) );
		params.add(new BasicNameValuePair("service", user.getService()) );

		//login 
		post = new HttpPost(LOGIN_URL);
		post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
//		post.addHeader("Referer", Referer);
		post.setHeader("Cookie", user.getCookies());
		httpResponse = httpclient.execute(post);
		cookieHeaders = httpResponse.getHeaders("Set-Cookie");
		user.setCookie(cookieHeaders);
		html = EntityUtils.toString(httpResponse.getEntity());
		Document htmljsoup = Jsoup.parse(html);
		post.releaseConnection();
		
		Element form  =htmljsoup.getElementById("login-form");
		if(form==null)
			log.info(html);
		else
			log.info(form.html());

		return true;
	}

	public boolean logoff(){
		return true;
	}

	public UMUser getUser() {
		return user;
	}

	public void setUser(UMUser user) {
		this.user = user;
	}

}
